package com.ssy.lingxi.platform.template.service.serviceimpl.inner;

import cn.hutool.core.collection.CollectionUtil;
import com.ssy.lingxi.common.constant.manage.ShopTypeEnum;
import com.ssy.lingxi.common.model.dto.MemberAndRoleIdDTO;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.platform.manage.api.feign.inner.ShopControllerFeign;
import com.ssy.lingxi.platform.manage.api.model.dto.common.CommonIdListDTO;
import com.ssy.lingxi.platform.manage.api.model.dto.shop.SelfBusinessShopLogoDTO;
import com.ssy.lingxi.platform.manage.api.model.vo.shop.SelfBusinessShopLogoVO;
import com.ssy.lingxi.platform.manage.api.model.vo.shop.ShopVO;
import com.ssy.lingxi.platform.template.api.model.dto.inner.MemberShopDTO;
import com.ssy.lingxi.platform.template.api.model.dto.inner.MemberShopListInnerDTO;
import com.ssy.lingxi.platform.template.api.model.dto.inner.MerchantLogoInnerDTO;
import com.ssy.lingxi.platform.template.api.model.dto.inner.UpdateShopStatusDTO;
import com.ssy.lingxi.platform.template.api.model.vo.inner.MemberShopListInnerVO;
import com.ssy.lingxi.platform.template.api.model.vo.inner.MerchantLogoInnerVO;
import com.ssy.lingxi.platform.template.service.constant.CommonBooleanEnum;
import com.ssy.lingxi.platform.template.service.entity.door.*;
import com.ssy.lingxi.platform.template.service.handler.async.PurchaseAsyncService;
import com.ssy.lingxi.platform.template.service.repository.*;
import com.ssy.lingxi.platform.template.service.service.inner.MemberShopInnerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author fhj
 * @version 2.0.0
 * @menu 会员店铺 - 内部接口 - 业务实现层
 * @date 2020/12/09
 */
@Slf4j
@Service
public class MemberShopInnerServiceImpl implements MemberShopInnerService {

    @Resource
    private MemberShopRepository memberShopRepository;
    @Resource
    private MemberChannelRepository memberChannelRepository;
    @Resource
    private MemberPurchaseRepository memberPurchaseRepository;
    @Resource
    private MemberProcessRepository memberProcessRepository;
    @Resource
    private MemberLogisticsRepository memberLogisticsRepository;
    @Resource
    private PurchaseAsyncService purchaseAsyncService;
    @Resource
    private ShopControllerFeign shopControllerFeign;

    /**
     * 更新店铺
     */
    @Override
    @Transactional
    public Wrapper<Void> updateShop(MemberShopDTO dto) {
        //根据会员ID和角色ID更新不为空的参数（会员名称、注册年数、信用积分、满意度）
        MemberShop memberShop = memberShopRepository.findByMemberIdAndRoleId(dto.getMemberId(), dto.getRoleId());
        MemberChannel memberChannel = memberChannelRepository.findByMemberIdAndRoleId(dto.getMemberId(), dto.getRoleId());
        MemberPurchase memberPurchase = memberPurchaseRepository.findByMemberIdAndRoleId(dto.getMemberId(), dto.getRoleId());
        MemberProcess memberProcess = memberProcessRepository.findByMemberIdAndRoleId(dto.getMemberId(), dto.getRoleId());
        MemberLogistics memberLogistics = memberLogisticsRepository.findByMemberIdAndRoleId(dto.getMemberId(), dto.getRoleId());

        if (memberShop != null) {
            memberShop.setMemberName(StringUtils.isNotEmpty(dto.getMemberName()) ? dto.getMemberName() : memberShop.getMemberName());
            memberShop.setRegisterYears(dto.getRegisterYears() != null ? dto.getRegisterYears() : memberShop.getRegisterYears());
            memberShop.setCreditPoint(dto.getCreditPoint() != null ? dto.getCreditPoint() : memberShop.getCreditPoint());
            memberShop.setAvgTradeCommentStar(dto.getAvgTradeCommentStar() != null ? dto.getAvgTradeCommentStar() : memberShop.getAvgTradeCommentStar());
            memberShop.setRegisteredCapital(StringUtils.isNotEmpty(dto.getRegisteredCapital()) ? dto.getRegisteredCapital() : memberShop.getRegisteredCapital());
            memberShop.setEstablishmentDate(StringUtils.isNotEmpty(dto.getEstablishmentDate()) ? dto.getEstablishmentDate() : memberShop.getEstablishmentDate());
            memberShop.setBusinessLicence(StringUtils.isNotEmpty(dto.getBusinessLicence()) ? dto.getBusinessLicence() : memberShop.getBusinessLicence());
            memberShop.setRegisterArea(StringUtils.isNotEmpty(dto.getRegisterArea()) ? dto.getRegisterArea() : memberShop.getRegisterArea());
            memberShop.setRegisterAddress(StringUtils.isNotEmpty(dto.getRegisterAddress()) ? dto.getRegisterAddress() : memberShop.getRegisterAddress());
            memberShopRepository.saveAndFlush(memberShop);
        }
        if (memberChannel != null) {
            memberChannel.setMemberName(StringUtils.isNotEmpty(dto.getMemberName()) ? dto.getMemberName() : memberChannel.getMemberName());
            memberChannel.setRegisterYears(dto.getRegisterYears() != null ? dto.getRegisterYears() : memberChannel.getRegisterYears());
            memberChannel.setCreditPoint(dto.getCreditPoint() != null ? dto.getCreditPoint() : memberChannel.getCreditPoint());
            memberChannel.setAvgTradeCommentStar(dto.getAvgTradeCommentStar() != null ? dto.getAvgTradeCommentStar() : memberChannel.getAvgTradeCommentStar());
            memberChannel.setRegisteredCapital(StringUtils.isNotEmpty(dto.getRegisteredCapital()) ? dto.getRegisteredCapital() : memberChannel.getRegisteredCapital());
            memberChannel.setEstablishmentDate(StringUtils.isNotEmpty(dto.getEstablishmentDate()) ? dto.getEstablishmentDate() : memberChannel.getEstablishmentDate());
            memberChannel.setBusinessLicence(StringUtils.isNotEmpty(dto.getBusinessLicence()) ? dto.getBusinessLicence() : memberChannel.getBusinessLicence());
            memberChannel.setRegisterArea(StringUtils.isNotEmpty(dto.getRegisterArea()) ? dto.getRegisterArea() : memberChannel.getRegisterArea());
            memberChannel.setRegisterAddress(StringUtils.isNotEmpty(dto.getRegisterAddress()) ? dto.getRegisterAddress() : memberChannel.getRegisterAddress());
            memberChannelRepository.saveAndFlush(memberChannel);
        }
        if (memberPurchase != null) {
            memberPurchase.setMemberName(StringUtils.isNotEmpty(dto.getMemberName()) ? dto.getMemberName() : memberPurchase.getMemberName());
            memberPurchase.setRegisterYears(dto.getRegisterYears() != null ? dto.getRegisterYears() : memberPurchase.getRegisterYears());
            memberPurchase.setCreditPoint(dto.getCreditPoint() != null ? dto.getCreditPoint() : memberPurchase.getCreditPoint());
            memberPurchase.setAvgTradeCommentStar(dto.getAvgTradeCommentStar() != null ? dto.getAvgTradeCommentStar() : memberPurchase.getAvgTradeCommentStar());
            memberPurchase.setRegisteredCapital(StringUtils.isNotEmpty(dto.getRegisteredCapital()) ? dto.getRegisteredCapital() : memberPurchase.getRegisteredCapital());
            memberPurchase.setEstablishmentDate(StringUtils.isNotEmpty(dto.getEstablishmentDate()) ? dto.getEstablishmentDate() : memberPurchase.getEstablishmentDate());
            memberPurchase.setBusinessLicence(StringUtils.isNotEmpty(dto.getBusinessLicence()) ? dto.getBusinessLicence() : memberPurchase.getBusinessLicence());
            memberPurchase.setRegisterArea(StringUtils.isNotEmpty(dto.getRegisterArea()) ? dto.getRegisterArea() : memberPurchase.getRegisterArea());
            memberPurchase.setRegisterAddress(StringUtils.isNotEmpty(dto.getRegisterAddress()) ? dto.getRegisterAddress() : memberPurchase.getRegisterAddress());
            memberPurchaseRepository.saveAndFlush(memberPurchase);
        }
        if (memberProcess != null) {
            memberProcess.setMemberName(StringUtils.isNotEmpty(dto.getMemberName()) ? dto.getMemberName() : memberProcess.getMemberName());
            memberProcess.setRegisterYears(dto.getRegisterYears() != null ? dto.getRegisterYears() : memberProcess.getRegisterYears());
            memberProcess.setCreditPoint(dto.getCreditPoint() != null ? dto.getCreditPoint() : memberProcess.getCreditPoint());
            memberProcess.setAvgTradeCommentStar(dto.getAvgTradeCommentStar() != null ? dto.getAvgTradeCommentStar() : memberProcess.getAvgTradeCommentStar());
            memberProcess.setRegisteredCapital(StringUtils.isNotEmpty(dto.getRegisteredCapital()) ? dto.getRegisteredCapital() : memberProcess.getRegisteredCapital());
            memberProcess.setEstablishmentDate(StringUtils.isNotEmpty(dto.getEstablishmentDate()) ? dto.getEstablishmentDate() : memberProcess.getEstablishmentDate());
            memberProcess.setBusinessLicence(StringUtils.isNotEmpty(dto.getBusinessLicence()) ? dto.getBusinessLicence() : memberProcess.getBusinessLicence());
            memberProcess.setRegisterArea(StringUtils.isNotEmpty(dto.getRegisterArea()) ? dto.getRegisterArea() : memberProcess.getRegisterArea());
            memberProcess.setRegisterAddress(StringUtils.isNotEmpty(dto.getRegisterAddress()) ? dto.getRegisterAddress() : memberProcess.getRegisterAddress());
            memberProcessRepository.saveAndFlush(memberProcess);
        }
        if (memberLogistics != null) {
            memberLogistics.setMemberName(StringUtils.isNotEmpty(dto.getMemberName()) ? dto.getMemberName() : memberLogistics.getMemberName());
            memberLogistics.setRegisterYears(dto.getRegisterYears() != null ? dto.getRegisterYears() : memberLogistics.getRegisterYears());
            memberLogistics.setCreditPoint(dto.getCreditPoint() != null ? dto.getCreditPoint() : memberLogistics.getCreditPoint());
            memberLogistics.setAvgTradeCommentStar(dto.getAvgTradeCommentStar() != null ? dto.getAvgTradeCommentStar() : memberLogistics.getAvgTradeCommentStar());
            memberLogistics.setRegisteredCapital(StringUtils.isNotEmpty(dto.getRegisteredCapital()) ? dto.getRegisteredCapital() : memberLogistics.getRegisteredCapital());
            memberLogistics.setEstablishmentDate(StringUtils.isNotEmpty(dto.getEstablishmentDate()) ? dto.getEstablishmentDate() : memberLogistics.getEstablishmentDate());
            memberLogistics.setBusinessLicence(StringUtils.isNotEmpty(dto.getBusinessLicence()) ? dto.getBusinessLicence() : memberLogistics.getBusinessLicence());
            memberLogistics.setRegisterArea(StringUtils.isNotEmpty(dto.getRegisterArea()) ? dto.getRegisterArea() : memberLogistics.getRegisterArea());
            memberLogistics.setRegisterAddress(StringUtils.isNotEmpty(dto.getRegisterAddress()) ? dto.getRegisterAddress() : memberLogistics.getRegisterAddress());
            memberLogisticsRepository.saveAndFlush(memberLogistics);
        }

        //同步各个门户后顺便更新采购服务的询价、招标、竞价, 根据会员ID和角色ID更新信用分
        if (dto.getCreditPoint() != null) {
            purchaseAsyncService.updateCreditPoint(dto.getMemberId(), dto.getRoleId(), dto.getCreditPoint());
        }

        return Wrapper.success();
    }

    /**
     * 更新店铺状态（可以是一个角色的禁用与启用，也可以是一个会员下的某个角色的禁用与启用）
     */
    @Override
    @Transactional
    public Wrapper<Void> updateShopStatus(UpdateShopStatusDTO dto) {
        //根据会员ID和角色ID更新状态
        if (dto.getMemberId() != null) {
            MemberShop memberShop = memberShopRepository.findByMemberIdAndRoleId(dto.getMemberId(), dto.getRoleId());
            MemberChannel memberChannel = memberChannelRepository.findByMemberIdAndRoleId(dto.getMemberId(), dto.getRoleId());
            MemberPurchase memberPurchase = memberPurchaseRepository.findByMemberIdAndRoleId(dto.getMemberId(), dto.getRoleId());
            MemberProcess memberProcess = memberProcessRepository.findByMemberIdAndRoleId(dto.getMemberId(), dto.getRoleId());
            MemberLogistics memberLogistics = memberLogisticsRepository.findByMemberIdAndRoleId(dto.getMemberId(), dto.getRoleId());

            if (memberShop != null) {
                memberShop.setStatus(dto.getStatus());
                memberShopRepository.saveAndFlush(memberShop);
            }
            if (memberChannel != null) {
                memberChannel.setStatus(dto.getStatus());
                memberChannelRepository.saveAndFlush(memberChannel);
            }
            if (memberPurchase != null) {
                memberPurchase.setStatus(dto.getStatus());
                memberPurchaseRepository.saveAndFlush(memberPurchase);
            }
            if (memberProcess != null) {
                memberProcess.setStatus(dto.getStatus());
                memberProcessRepository.saveAndFlush(memberProcess);
            }
            if (memberLogistics != null) {
                memberLogistics.setStatus(dto.getStatus());
                memberLogisticsRepository.saveAndFlush(memberLogistics);
            }

            return Wrapper.success();
        }

        //根据角色ID更新店铺状态
        List<MemberShop> memberShopList = memberShopRepository.findByRoleId(dto.getRoleId());
        List<MemberChannel> memberChannelList = memberChannelRepository.findByRoleId(dto.getRoleId());
        List<MemberPurchase> memberPurchaseList = memberPurchaseRepository.findByRoleId(dto.getRoleId());
        List<MemberProcess> memberProcessList = memberProcessRepository.findByRoleId(dto.getRoleId());
        List<MemberLogistics> memberLogisticsList = memberLogisticsRepository.findByRoleId(dto.getRoleId());

        if (CollectionUtil.isNotEmpty(memberShopList)) {
            memberShopRepository.saveAll(memberShopList.stream().peek(memberShop -> memberShop.setStatus(dto.getStatus())).collect(Collectors.toList()));
        }
        if (CollectionUtil.isNotEmpty(memberChannelList)) {
            memberChannelRepository.saveAll(memberChannelList.stream().peek(memberChannel -> memberChannel.setStatus(dto.getStatus())).collect(Collectors.toList()));
        }
        if (CollectionUtil.isNotEmpty(memberPurchaseList)) {
            memberPurchaseRepository.saveAll(memberPurchaseList.stream().peek(memberPurchase -> memberPurchase.setStatus(dto.getStatus())).collect(Collectors.toList()));
        }
        if (CollectionUtil.isNotEmpty(memberProcessList)) {
            memberProcessRepository.saveAll(memberProcessList.stream().peek(memberProcess -> memberProcess.setStatus(dto.getStatus())).collect(Collectors.toList()));
        }
        if (CollectionUtil.isNotEmpty(memberLogisticsList)) {
            memberLogisticsRepository.saveAll(memberLogisticsList.stream().peek(memberLogistics -> memberLogistics.setStatus(dto.getStatus())).collect(Collectors.toList()));
        }

        return Wrapper.success();
    }

    /**
     * 店铺列表
     */
    @Override
    public Wrapper<List<MemberShopListInnerVO>> memberShopList(List<MemberShopListInnerDTO> dto) {
        //校验
        if (CollectionUtil.isEmpty(dto)) {
            return Wrapper.success(new ArrayList<>());
        }

        //根据会员ID获取所有会员店铺门户
        List<MemberShop> memberShops = memberShopRepository.findByMemberIdIn(
                dto.stream().map(MemberShopListInnerDTO::getMemberId).collect(Collectors.toList())
        );

        //组装
        List<MemberShopListInnerVO> memberShopListInnerVOList = dto.stream().map(a -> {
            //根据会员id和角色id获取对应的店铺门户
            MemberShop memberShop = memberShops.stream().filter(b ->
                    b.getMemberId().equals(a.getMemberId()) && b.getRoleId().equals(a.getRoleId())
            ).findFirst().orElse(null);

            //封装
            MemberShopListInnerVO memberShopListInnerVO = new MemberShopListInnerVO();
            memberShopListInnerVO.setMemberId(a.getMemberId());
            memberShopListInnerVO.setRoleId(a.getRoleId());
            memberShopListInnerVO.setLogo(memberShop != null ? memberShop.getLogo() : null);
            memberShopListInnerVO.setShopId(memberShop != null ? memberShop.getId() : null);
            return memberShopListInnerVO;
        }).collect(Collectors.toList());

        return Wrapper.success(memberShopListInnerVOList);
    }

    /**
     * 根据商城ID获取商家LOGO
     */
    @Override
    public Wrapper<List<MerchantLogoInnerVO>> findMerchantLogoByShopId(MerchantLogoInnerDTO dto) {
        //定义返回实体
        List<MerchantLogoInnerVO> merchantLogoInnerVOList;

        //调用平台后台服务 -> 根据商城ID获取商城
        CommonIdListDTO commonIdListDTO = new CommonIdListDTO();
        commonIdListDTO.setIdList(Stream.of(dto.getShopId()).collect(Collectors.toList()));
        Wrapper<List<ShopVO>> shopByIdListWrapper = shopControllerFeign.byShopIds(commonIdListDTO);
        if (shopByIdListWrapper.getCode() != ResponseCode.SUCCESS.getCode() && shopByIdListWrapper.getCode() <= 0) {
            log.error("调用平台管理服务失败：{}", shopByIdListWrapper.getMessage());
            return Wrapper.fail(ResponseCode.PT_CAN_T_GET_THE_MALL_ACCORDING_TO_THE_MALL_ID);
        }
        ShopVO shopVO = shopByIdListWrapper.getData().get(0);

        //case1: 企业商城;  case2: 渠道商城;  case3: 直接返回;
        if (shopVO.getType().equals(ShopTypeEnum.ENTERPRISE.getCode())) {
            //自营商城封装自营商城的LOGO和商城名称;  非自营商城封装店铺LOGO和店铺名称
            if (shopVO.getSelf().equals(CommonBooleanEnum.YES.getCode())) {
                SelfBusinessShopLogoDTO selfBusinessShopLogoDTO = new SelfBusinessShopLogoDTO();
                selfBusinessShopLogoDTO.setShopId(dto.getShopId());
                selfBusinessShopLogoDTO.setList(
                        dto.getList().stream().map(a -> {
                            MemberAndRoleIdDTO memberAndRoleIdDTO = new MemberAndRoleIdDTO();
                            memberAndRoleIdDTO.setMemberId(a.getMemberId());
                            memberAndRoleIdDTO.setRoleId(a.getRoleId());
                            return memberAndRoleIdDTO;
                        }).collect(Collectors.toList())
                );
                //调用模板管理服务-->获取自营商家的商城LOGO
                Wrapper<List<SelfBusinessShopLogoVO>> wrapper = shopControllerFeign.findSelfBusinessShopLogo(selfBusinessShopLogoDTO);
                if (shopByIdListWrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
                    log.error("调用平台管理服务失败：{}", shopByIdListWrapper.getMessage());
                    return Wrapper.fail(ResponseCode.SERVICE_PLATFORM_MANAGE_ERROR);
                }

                //组装
                List<SelfBusinessShopLogoVO> selfBusinessShopLogoVOList = wrapper.getData();
                merchantLogoInnerVOList = dto.getList().stream().map(a -> {
                    //根据会员id和角色id获取对应的自营商家
                    SelfBusinessShopLogoVO selfBusinessShopLogoVO = selfBusinessShopLogoVOList.stream().filter(b ->
                            b.getMemberId().equals(a.getMemberId()) && b.getMemberRoleId().equals(a.getRoleId())
                    ).findFirst().orElse(null);

                    //封装
                    MerchantLogoInnerVO merchantLogoInnerVO = new MerchantLogoInnerVO();
                    merchantLogoInnerVO.setMemberId(a.getMemberId());
                    merchantLogoInnerVO.setRoleId(a.getRoleId());
                    merchantLogoInnerVO.setLogo(selfBusinessShopLogoVO != null ? selfBusinessShopLogoVO.getLogoUrl() : null);
                    merchantLogoInnerVO.setName(selfBusinessShopLogoVO != null ? selfBusinessShopLogoVO.getName() : null);
                    return merchantLogoInnerVO;
                }).collect(Collectors.toList());

            } else {
                //根据会员ID获取所有会员店铺门户
                List<MemberShop> memberShops = memberShopRepository.findByMemberIdIn(
                        dto.getList().stream().map(MemberShopListInnerDTO::getMemberId).collect(Collectors.toList())
                );

                //组装
                merchantLogoInnerVOList = dto.getList().stream().map(a -> {
                    //根据会员id和角色id获取对应的店铺门户
                    MemberShop memberShop = memberShops.stream().filter(b ->
                            b.getMemberId().equals(a.getMemberId()) && b.getRoleId().equals(a.getRoleId())
                    ).findFirst().orElse(null);

                    //封装
                    MerchantLogoInnerVO merchantLogoInnerVO = new MerchantLogoInnerVO();
                    merchantLogoInnerVO.setMemberId(a.getMemberId());
                    merchantLogoInnerVO.setRoleId(a.getRoleId());
                    merchantLogoInnerVO.setLogo(memberShop != null ? memberShop.getLogo() : null);
                    merchantLogoInnerVO.setName(memberShop != null ? memberShop.getName() : null);
                    return merchantLogoInnerVO;
                }).collect(Collectors.toList());
            }
        } else if (ShopTypeEnum.checkChannelOrChannelSelf(shopVO.getType())) {
            //根据会员ID获取所有会员渠道门户
            List<MemberChannel> memberChannels = memberChannelRepository.findByMemberIdIn(
                    dto.getList().stream().map(MemberShopListInnerDTO::getMemberId).collect(Collectors.toList())
            );

            //组装
            merchantLogoInnerVOList = dto.getList().stream().map(a -> {
                //根据会员id和角色id获取对应的渠道门户
                MemberChannel memberChannel = memberChannels.stream().filter(b ->
                        b.getMemberId().equals(a.getMemberId()) && b.getRoleId().equals(a.getRoleId())
                ).findFirst().orElse(null);

                //封装
                MerchantLogoInnerVO merchantLogoInnerVO = new MerchantLogoInnerVO();
                merchantLogoInnerVO.setMemberId(a.getMemberId());
                merchantLogoInnerVO.setRoleId(a.getRoleId());
                merchantLogoInnerVO.setLogo(memberChannel != null ? memberChannel.getLogo() : null);
                merchantLogoInnerVO.setName(memberChannel != null ? memberChannel.getMemberName() : null);
                return merchantLogoInnerVO;
            }).collect(Collectors.toList());
        } else {
            //查询不到
            return Wrapper.fail(ResponseCode.PT_CAN_NOT_FIND_VENDOR_LOGO);
        }

        return Wrapper.success(merchantLogoInnerVOList);
    }
}
